﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace WoBian.DA
{
    /// <summary>
    /// 数据访问层扩展类
    /// </summary>
    public static class DataAccessExtension
    {
        public static T DataReaderToModel<T>(this IDataReader reader) where T : new()
        {
            T item = default(T);
            if (reader.Read())
            {
                item = new T();
                Type type = typeof(T);
                PropertyInfo[] infos = type.GetProperties();
                foreach (PropertyInfo info in infos)
                {
                    if (reader[info.Name] != null && reader[info.Name] != System.DBNull.Value)
                        info.SetValue(item, reader[info.Name], null);
                }
            }
            return item;
        }

        public static List<T> DataReaderToList<T>(this IDataReader reader) where T : new()
        {
            List<T> aList = new List<T>();
            while (reader.Read())
            {
                T item = new T();
                Type type = typeof(T);
                PropertyInfo[] infos = type.GetProperties();
                foreach (PropertyInfo info in infos)
                {
                    if (reader[info.Name] != null && reader[info.Name] != System.DBNull.Value)
                    info.SetValue(item, reader[info.Name], null);
                }
                aList.Add(item);
            }
            return aList;
        }
        public static T DataRowToModel<T>(this DataRow row) where T : new()
        {
            T item = default(T);
            if (row != null)
            {
                item = new T();
                Type type = typeof(T);
                PropertyInfo[] infos = type.GetProperties();
                foreach (PropertyInfo info in infos)
                {
                    if (row[info.Name] != null && row[info.Name] != System.DBNull.Value)
                        info.SetValue(item, row[info.Name], null);
                }
            }
            return item;
        }

        public static List<T> DataTableToList<T>(this DataTable table) where T : new()
        {
            List<T> aList = new List<T>();
            if (table != null)
            {
                foreach (DataRow dr in table.Rows)
                {
                    T item = new T();
                    item = dr.DataRowToModel<T>();
                    aList.Add(item);
                }
            }
            return aList;
        }

        public static void AddParameters(this IDbCommand aCmd, IEnumerable<IDataParameter> aParameters)
        {
            aCmd.Parameters.Clear();
            foreach (IDataParameter p in aParameters)
            {
                aCmd.Parameters.Add(p);
            }
        }
    }
}
